package com.ziroom.crm.mq.core.processor.retry.config;

import com.ziroom.crm.mq.core.config.MqConfig;
import com.ziroom.crm.mq.core.processor.retry.DefaultReConsumeRetryProcessor;
import com.ziroom.crm.mq.core.retry.DelayContext;
import com.ziroom.crm.mq.core.retry.RetryConst;
import com.ziroom.crm.mq.core.retry.RetryContext;
import com.ziroom.crm.mq.core.retry.delay.ExponentialDelayPolicy;
import com.ziroom.crm.mq.core.spi.SpiAlias;

/**
 * 用于解析配置，消费端立即重试，数量策略
 * <p/>
 *
 * @author WeiShaoying
 * @date Created in 2020年09月16日 16:05
 * @since 1.0.0
 */
@SpiAlias(value = RetryConst.DELAY_POLICY_EXPONENTIAL, group = DefaultReConsumeRetryProcessor.GROUP_RECONSUME)
public class ReConsumeExponentialDelayPolicy extends ExponentialDelayPolicy {

    private static final long ONE_HOUR = 3600 * 1000L;

    @Override
    public DelayContext start(RetryContext retryContext) {
        // 通过重试时长 + 重试次数 = 固定次数的指数退避延时
        int period = Integer.parseInt(MqConfig.getConfig(MqConfig.RETRY_RECONSUME_DELAY_PERIOD));
        // 下一次的持久化次数
        int persistenceRetryCount = retryContext.getRetryCount();
        double multiplier = this.getMultiplier();

        // 上一次的延时时长
        long initialInterval = (long) Math.pow(multiplier,persistenceRetryCount) * period;
        return new ExponentialDelayContext(initialInterval, multiplier, ONE_HOUR);
    }
}
